<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入流程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请输入流程实例状态" clearable>
          <el-option
            v-for="dict in dict.type.procins_state_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="完成日期" prop="completeDate">
              <el-date-picker clearable
                              v-model="queryParams.completeDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择完成日期">
              </el-date-picker>
            </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="instanceList">
      <!--      <el-table-column label="ID" align="center" prop="id"/>-->
      <el-table-column label="流程名称" align="center" prop="modelName"/>
      <el-table-column label="业务主题" align="center" prop="title"/>

      <!--      <el-table-column label="流程实例状态" align="center" prop="state"/>--> <!--:filters="filters"
                       :filter-method="filterMethod"-->
      <el-table-column label="状态" align="center" prop="state" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.procins_state_type" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成日期" align="center" prop="completeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.completeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleDetails(scope.row)"
          >详情
          </el-button>
          <el-button
            v-if="scope.row.state && scope.row.state==1"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleRevoke(scope.row)"
          >撤回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情页面 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :rules="rules">
      <el-tabs v-model="activeName" @tab-click="handleClick" tab-position="left">
        <el-tab-pane label="表单信息" name="first">
          <el-col :span="16" :offset="4">
            <div class="test-form">
              <!--              <parser :key="new Date().getTime()" :form-conf="variablesData"/>-->
              <parser :key="new Date().getTime()" :form-conf="variablesData" @submit="submitForm" ref="parser"/>
            </div>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="second">
          <div>
            <flow-view :flowData="flowData"/>
          </div>
        </el-tab-pane>
        <!--流程流转记录-->
        <!--        <el-tab-pane label="流转记录" name="fourth">
                  <el-col :span="16" :offset="4">
                    <div class="block">
                      <el-timeline>
                        <el-timeline-item
                          v-for="(item,index ) in flowRecordList"
                          :key="index">
                          &lt;!&ndash;                  :icon="setIcon(item.finishTime)"
                                            :color="setColor(item.finishTime)"&ndash;&gt;

                          <p style="font-weight: 700">{{ item.taskName }}</p>
                          <el-card :body-style="{ padding: '10px' }">
                            <el-descriptions class="margin-top" :column="1" size="small" border>
                              <el-descriptions-item v-if="item.handlerUserName" label-class-name="my-label">
                                <template slot="label"><i class="el-icon-user"></i>办理人</template>
                                {{ item.handlerUserName }}
                                <el-tag type="info" size="mini">{{ item.deptName }}</el-tag>
                              </el-descriptions-item>

                              <el-descriptions-item v-if="item.candidate" label-class-name="my-label">
                                <template slot="label"><i class="el-icon-user"></i>候选办理</template>
                                {{ item.candidate }}
                              </el-descriptions-item>

                              <el-descriptions-item label-class-name="my-label">
                                <template slot="label"><i class="el-icon-date"></i>接收时间</template>
                                {{ item.createTime }}
                              </el-descriptions-item>

                              <el-descriptions-item v-if="item.finishTime" label-class-name="my-label">
                                <template slot="label"><i class="el-icon-date"></i>处理时间</template>
                                {{ item.createTime }}
                              </el-descriptions-item>

                              <el-descriptions-item v-if="item.duration" label-class-name="my-label">
                                <template slot="label"><i class="el-icon-time"></i>耗时</template>
                                {{ item.duration }}
                              </el-descriptions-item>

                              <el-descriptions-item v-if="item.comment" label-class-name="my-label">
                                <template slot="label"><i class="el-icon-tickets"></i>处理意见</template>
                                {{ item.comment }}
                              </el-descriptions-item>
                            </el-descriptions>
                          </el-card>
                        </el-timeline-item>
                      </el-timeline>
                    </div>
                  </el-col>
                </el-tab-pane>-->
        <!--        <el-tab-pane label="流转记录" name="fourth">



                </el-tab-pane>-->
        <!--                <el-button  icon="el-icon-edit-outline" type="primary" size="mini" @click="handleAssign">转办</el-button>-->
        <!--                <el-button  icon="el-icon-edit-outline" type="primary" size="mini" @click="handleDelegate">签收</el-button>-->
        <!--              <el-button icon="el-icon-refresh-left" type="warning" size="mini" @click="handleReturn">退回</el-button>-->
        <!--              <el-button icon="el-icon-circle-close" type="danger" size="mini" @click="handleReject">驳回</el-button>-->

      </el-tabs>
      <!--      <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>-->
    </el-dialog>

    <!-- 添加或修改自定义流程实例对话框 -->
    <!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="流程模型ID" prop="modelId">
              <el-input v-model="form.modelId" placeholder="请输入流程模型ID"/>
            </el-form-item>
            <el-form-item label="表单ID" prop="formId">
              <el-input v-model="form.formId" placeholder="请输入表单ID"/>
            </el-form-item>
            <el-form-item label="BPMN流程实例ID" prop="instanceId">
              <el-input v-model="form.instanceId" placeholder="请输入BPMN流程实例ID"/>
            </el-form-item>
            <el-form-item label="业务主题" prop="title">
              <el-input v-model="form.title" placeholder="请输入业务主题"/>
            </el-form-item>
            <el-form-item label="业务表KEY" prop="businessKey">
              <el-input v-model="form.businessKey" placeholder="请输入业务表KEY"/>
            </el-form-item>
            <el-form-item label="流程实例状态" prop="state">
              <el-input v-model="form.state" placeholder="请输入流程实例状态"/>
            </el-form-item>
            <el-form-item label="完成日期" prop="completeDate">
              <el-date-picker clearable
                              v-model="form.completeDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择完成日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="租户ID" prop="tenantId">
              <el-input v-model="form.tenantId" placeholder="请输入租户ID"/>
            </el-form-item>
            <el-form-item label="删除标志" prop="delFlag">
              <el-input v-model="form.delFlag" placeholder="请输入删除标志"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>-->
  </div>
</template>

<script>
import {
  myListInstance,
  getInstance,
  getFormByInsId,
  addInstance,
  updateInstance,
  revokeInstance,
  getDynamicModelPic
} from "@/api/process/ins";
import FlowView from "../todo/flowview.vue";
import {getForm, addDeployForm, listForm} from "@/api/process/form";
import Parser from '@/components/parser/Parser'
import {getUser} from "@/api/system/user";
import FlowUser from '@/components/flow/User'

export default {
  name: "Instance",
  components: {Parser, FlowView, FlowUser,},
  dicts: ['procins_state_type'],
  data() {
    return {
      filters: [
        {text: "已撤销", value: 5},
        {text: "‘电子工程’", value: 1}
      ],
      user: {},
      roleGroup: {},
      postGroup: {},
      activeTab: "userinfo",
      variablesData: {}, // 流程变量数据
      flowRecordList: [], // 流程流转数据
      userVisible: false,
      activeName: 'first',
      // 用户列表
      userList: this.users,
      textarea: '',
      // 模型xml数据
      xmlData: "",
      flowData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自定义流程实例表格数据
      instanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        modelName: null,
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        formId: null,
        instanceId: null,
        title: null,
        businessKey: null,
        state: null,
        completeDate: null,
        tenantId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelId: [
          {required: true, message: "流程模型ID不能为空", trigger: "blur"}
        ],
        instanceId: [
          {required: true, message: "BPMN流程实例ID不能为空", trigger: "blur"}
        ],
        delFlag: [
          {required: true, message: "删除标志不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    filterMethod(value, row) {
      console.log("=====================")
      console.log(value)
      return row.state === value;
    },
    /** 查询自定义流程实例列表 */
    getList() {
      this.loading = true;
      myListInstance(this.queryParams).then(response => {
        this.instanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleClick(tab, event) {
      let selected = tab.name; // 选中的
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        modelId: null,
        formId: null,
        instanceId: null,
        title: null,
        businessKey: null,
        state: null,
        completeDate: null,
        tenantId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自定义流程实例";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInstance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改自定义流程实例";
      });
    },
    handleDetails(row) {

      const id = row.id // 任务ID
      this.id = id;
      // 一次性查询所有相关信息
      this.reset();
      // 设置为发起人，并查询发起人信息
      this.activeName = 'first'
/*      // 1. 发起人
      getUser(row.initiator).then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });*/
      // 2. 根据ID查询启动表单变量（之前都作为了流程变量存入）
      // 表单
      getFormByInsId(row.id).then(response => {
        console.log(response)
        this.variablesData = response.data.variables;
      });
      // 3. 动态流程图
      getDynamicModelPic(row.id).then(res => {
        this.flowData = res.data;
      });
      /*      // 4. 流转记录
            let query = {};
            query.processInstanceId = row.processInstanceId
            listRecord(query).then(res => {
              this.flowRecordList = res.data;
            });*/
      // 打开页面
      this.open = true;
      this.title = "流程详情";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInstance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInstance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 撤销流程按钮操作 */
    handleRevoke(row) {
      let data = {};
      data.id=row.id;
      this.$prompt('撤回后，该审批流程将自动结束', "撤回理由", {
        cancelButtonText: "取消",
        confirmButtonText: "撤回",
      }).then(({ value }) => {
        data.reason=value;
        revokeInstance(data).then(response => {
          this.handleQuery();
          this.$modal.msgSuccess("撤回成功");
        });
      }).catch(() => {});
/*      let data = {};
      data.processInstanceId = row.instanceId;
      this.$modal.confirm('是否撤销当前流程实例').then(function () {
        return revokeInstance(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {
      });*/
    }
  }
};
</script>
